package com.pepsico.introjava.labs;

import com.pepsico.introjava.exceptions.InvalidParameterException;
import java.util.*;

public class Company extends TaxEntity
{
	private Collection<Employee> employees;

	public Company(String name)
	{
		super(name);

		employees = new TreeSet<Employee>(new Comparator<TaxEntity>() {
			public int compare(TaxEntity arg0, TaxEntity arg1)
			{
				return arg1.getName().compareTo(arg0.getName());
			}
		}
		);
	}

	public void hire(Employee newHire)
	{
		if (newHire != null)
			employees.add(newHire);
		else
			throw new InvalidParameterException("Newhire", "Must be an object",
					null);
	}

	public void downsize(int amount)
	{
		Iterator<Employee> it = employees.iterator();
		while (it.hasNext() && amount-- > 0)
		{
			it.next();
			it.remove();
		}
	}

	@Override
	public float pay()
	{
		float totalAccumulatedNet = 0;
		for (Employee current : employees)
		{
			System.out.println("paying " + current);
			totalAccumulatedNet += current.pay();
		}
		return totalAccumulatedNet;
	}

	@Override
	protected String getNameValidationExpression()
	{
		return "^.{1,30}$";
	}

	public static void main(String[] args)
	{

		try
		{
			Company pep = new Company("Pepsi");
			Employee e1 = new Employee("Joe Smith", 100);
			Employee e2 = new Employee("Mary Contrary", 200);

			pep.hire(e1);
			pep.hire(e2);
			pep.hire(new Employee("Jane Smith", 100));
			pep.hire(new Employee("Margaret Jones", 100));
			pep.hire(new Employee("Jane Smith", 100));
			pep.hire(e1);

			float total = pep.pay();
			pep.downsize(3);

			System.out.println(total);

			Payable[] items = new Payable[4];
			items[0] = pep;
			items[1] = e1;
			items[2] = e2;
			items[3] = new HotDogVendor();

			payEntities(items);

			System.out.println("***************************");
			System.out.println(pep);
			System.out.println(e1);
		} catch (InvalidParameterException e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
			System.exit(2);
		} finally
		{
			System.out.println("**** finally ****");
		}

	}

	public static void payEntities(Payable[] entities)
	{
		for (int i = 0; i < entities.length; i++)
		{
			System.out.println(" I just paid  $" + entities[i].pay());
		}
	}

}
